package cn.lyjuan.android.mylibrary.frame.load.impl;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;

import cn.lyjuan.android.mylibrary.frame.load.IFragmentLoad;
import cn.lyjuan.android.mylibrary.frame.load.fragment.AbstractLoadFailedFragment;

/**
 * Created by chad on 14/11/2017.
 */

public abstract class AbstractLoad implements IFragmentLoad
{
    public static String FRAGMENT_TAG = "fragment_tag";

    protected Activity context;

    protected FragmentManager fm;

    /**
     * 正常时显示的Fragment
     */
    protected Fragment normalFragment;


    protected AbstractLoadFailedFragment failedFragment;

    /**
     * Fragment的容器ID
     */
    protected int containerId;

    public AbstractLoad(Activity context)
    {
        this.context = context;
        this.fm = context.getFragmentManager();
    }

    public AbstractLoad(Activity context, Fragment normal, int containerId)
    {
        this(context);
        this.normalFragment = normal;
        this.containerId = containerId;
    }

    @Override
    public Fragment normalFragment()
    {
        return normalFragment;
    }

    @Override
    public int containerId()
    {
        return containerId;
    }

    @Override
    public String fragmentTag()
    {
        return FRAGMENT_TAG;
    }

    @Override
    public void inflate()
    {
        Fragment exist = fm.findFragmentByTag(fragmentTag());

        Fragment fragment = shouldNormal() ? normalFragment() : failedFragment().setOnReloadListener(this);

        if (exist == fragment)
            return;// 同样的fragment不重新加载

        fm
                .beginTransaction()
                .replace(containerId(), fragment, fragmentTag())
                .commit();
    }

    @Override
    public void onReload()
    {
        this.inflate();
    }
}
